package com.mt.fpb.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mt.fpb.mapper.RxEmployeeMapper;
import com.mt.fpb.mapper.UserMapper;
import com.mt.fpb.mapper.WxProductMapper;
import com.mt.fpb.mapper.WxProductOrderMapper;

import com.mt.fpb.model.RxEmployee;
import com.mt.fpb.model.WxProduct;
import com.mt.fpb.model.WxProductOrder;
import com.mt.fpb.model.dto.ProductDto;
import com.mt.fpb.model.dto.ProductOrderDto;
import com.mt.fpb.model.vo.CommonResult;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;

@RestController
@RequestMapping("product")
public class ProductController {

    @Autowired
    private WxProductMapper productMapper;

    @Autowired
    private WxProductOrderMapper productOrderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RxEmployeeMapper rxEmployeeMapper;

    //账户总金额，本金加上已产生的收益
    //private float totalMoney;



    /**
     * 获取内部员工购买的产品列表
     * 收益明细
     * @return
     */
    @GetMapping("getEmployeeProduct")
    public CommonResult getUserProduct(String employeeId){
        List<ProductOrderDto> orderList = new ArrayList<ProductOrderDto>();

        QueryWrapper<WxProductOrder> queryWrapper = new QueryWrapper<WxProductOrder>();
        //通过员工id查询已购买的产品列表
        queryWrapper.eq("employee_id",employeeId);
        List<WxProductOrder> list = productOrderMapper.findProductList(employeeId);

        //创建封装数据的对象
        ProductOrderDto p = null;
        //遍历从数据库中取到的订单数据
        for(WxProductOrder order : list){
            String orderStatus = order.getOrderStatus();
            //判断订单的状态
            if("1".equals(orderStatus)){
                String productId = order.getProductId();
                System.out.println("productId:"+productId);
                WxProduct product = productMapper.selectById(productId);
                String productName = product.getProductName();
                float profit = product.getProfit();
                System.out.println("profit:"+profit);
                //获取当前产品的锁定天数
                int day = product.getLockTime();
                System.out.println("获取到的产品day:"+day);

                String orderId = order.getId();
                System.out.println("orderId:"+orderId);
                //获取员工id
                String employeeId1 = order.getEmployeeId();
                System.out.println("employeeId1:"+employeeId1);

                float payMoney = order.getPayMoney();
                float orderMoney = order.getOrderMoney();
                //预期收益金额
                float exProfit = (payMoney*profit*day)/365;
                DecimalFormat decimalFormat=new DecimalFormat(".00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
                String exProfitStr = decimalFormat.format(exProfit);

                Date endTime = order.getEndTime();
                System.out.println("endTime:"+endTime);
                //将数据库中取到的截止时间转换为时间戳
                long endTimes = endTime.getTime();
                /*Date  startTime =order.getStartTime();
                //将数据库中取到的开始时间转换为时间戳
                long startTimes = startTime.getTime();*/
                //获取当前时间毫秒数，与到期时间毫秒数计算得到到期的时间毫秒数
                long currentTime = System.currentTimeMillis();

                //到期时间的时间戳
                long value = endTimes-currentTime;
                //System.out.println("到期时间戳value:"+value);
                long days  = value/(1000 * 24 * 3600);

                //创建返回前端数据的对象
                p = new ProductOrderDto();
                p.setProductName(productName);
                p.setPayMoney(payMoney);
                p.setEndTime(endTime);
                //p.setOrderMoney(exProfit);
                p.setOrderMoney(Float.parseFloat(exProfitStr));
                p.setExpirationDay(days);
                p.setOrderId(orderId);
                p.setEmployeeId(employeeId1);

                orderList.add(p);


            }
        }
        return CommonResult.success(orderList);
    }




    /**
     *我的资产接口
     * @Author yu
     * @date 2021/8/11 16:33
     * @Param [employeeId]
     * @return com.mt.fpb.model.vo.CommonResult
     **/

    @GetMapping("getMyAssets")
    public CommonResult<Map<String,Object>> getMAssets(String employeeId){
        Map<String,Object> map = new HashMap();
        List<ProductOrderDto> orderList = new ArrayList<ProductOrderDto>();

        //查询产品表，获取产品表中的最高利率
        WxProduct wxProduct = productMapper.getMaxProfit();
        float maxProfit = wxProduct.getProfit();
        //将小数转化成百分数
        DecimalFormat df = new DecimalFormat("0%");
        String r = df.format(maxProfit);
        //System.out.println("maxProfit:"+r);

        QueryWrapper<WxProductOrder> queryWrapper = new QueryWrapper<WxProductOrder>();
        //通过员工id查询已购买的产品列表
        queryWrapper.eq("employee_id",employeeId);
        List<WxProductOrder> list = productOrderMapper.findProductList(employeeId);
        System.out.println("list:"+list);

        //通过员工id查询员工的手机号码
        RxEmployee rxEmployee = rxEmployeeMapper.selectById(employeeId);
        String phoneNumber = rxEmployee.getPhoneNumber();
        System.out.println("phoneNumber:"+phoneNumber);
        //计算账户的总金额
        float totalMoney =0f;
//        DecimalFormat decimalFormat=new DecimalFormat(".00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
//        String totalMoneyStr = decimalFormat.format(totalMoney);
        //创建封装数据的对象
        ProductOrderDto p = null;
        //遍历从数据库中取到的订单数据

            for(WxProductOrder order : list){
                String orderStatus = order.getOrderStatus();
                System.out.println("orderStatus:"+orderStatus);
                //判断订单的状态
                if("1".equals(orderStatus)){
                    String productId = order.getProductId();
                    System.out.println("productId:"+productId);
                    WxProduct product = productMapper.selectById(productId);
                    String productName = product.getProductName();
                    float orderMoney = order.getOrderMoney();
                    totalMoney+=orderMoney;

                    //获取第一条订单的购买金额即payMoney
                    float payMoney = order.getPayMoney();
                    Date endTime = order.getEndTime();
                    System.out.println("endTime:"+endTime);
                    //将数据库中取到的截止时间转换为时间戳
                    long endTimes = endTime.getTime();
                /*Date  startTime =order.getStartTime();
                //将数据库中取到的开始时间转换为时间戳
                long startTimes = startTime.getTime();*/
                    //获取当前时间毫秒数，与到期时间毫秒数计算得到到期的时间毫秒数
                    long currentTime = System.currentTimeMillis();

                    //到期时间的时间戳
                    long value = endTimes-currentTime;
                    //System.out.println("到期时间戳value:"+value);
                    long days  = value/(1000 * 24 * 3600);

                    //通过peyMoney降序查找 取出最后一个paymoney 即为当前订单的最大支付金额
                    //maxMoney = payMoney;
                    //orderList.add(p);

                }
//                DecimalFormat decimalFormat=new DecimalFormat(".00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
//                String totalMoneyStr = decimalFormat.format(totalMoney);
                BigDecimal b = new BigDecimal(totalMoney);
                double  totalMoneyStr = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();//保留两位小数


                //通过当前订单的最高金额去获取产品id
                WxProductOrder productOrder =  productOrderMapper.getMaxPayMoneyOrder(employeeId);
                if(productOrder !=null){
                    //拿到当前最大订单的产品id
                    String productId =  productOrder.getProductId();
                    float maxMoney = productOrder.getPayMoney();

                    //通过产品id拿到当前产品的利率
                    QueryWrapper<WxProduct> q1 = new QueryWrapper();
                    q1.eq("product_id",productId);
                    WxProduct wxProduct1 =productMapper.selectOne(q1);
                    float profit= wxProduct1.getProfit();
                    //获取产品的锁定时间
                    int day = wxProduct1.getLockTime();
                    System.out.println("数据库中获取到的锁定天数:"+day);
                    System.out.println("profit:"+profit);
                    //计算最大订单的预期收益
                    float earning = (maxMoney*profit*day)/365;
                    BigDecimal b1 = new BigDecimal(earning);
                    double earingStr = b1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();//保留两位小数

//                    DecimalFormat decimalFormat1=new DecimalFormat(".00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
//                    String earingStr = decimalFormat1.format(earning);
                    System.out.println("earning:"+earning);
                    System.out.println("maxMoney:"+maxMoney);
                    map.put("phone",phoneNumber);
                    //map.put("totalMoney",totalMoney);
                    map.put("totalMoney",totalMoneyStr);
                    map.put("maxProfit",r);
                    map.put("maxMoney",maxMoney);
                    //map.put("earning",earning);
                    map.put("earning",earingStr);
                    // map.put("orderList",orderList);
                }else{
                    map.put("phone",phoneNumber);
                    map.put("totalMoney",totalMoney);
                    map.put("maxProfit",r);
                    map.put("maxMoney",0);
                    map.put("earning",0);
                }




            }
            System.out.println("totalMoney:"+totalMoney);
            System.out.println(orderList);
            return CommonResult.success(map);


    }

    /**
     * 产品列表接口
     * 根据不同的角色显示当前用户每个产品的可购买额度
     * @param employeeId
     * @return
     */
    @GetMapping("getProductByEmployeeId")
    public CommonResult getProductByUserId(String employeeId){
        Map <String,Object> map = new HashMap<>();
        System.out.println("employeeId："+employeeId);
        List<ProductDto> list = new ArrayList<ProductDto>();
        //已经购买产品的金额
        float payMoneyed = 0;

        //预期收益
        float expectation = 0f;
        String  expectationStr="0";
        //总金额
        float totalMoney = 0f;
        //查询订单表
        List<Map> ordermap = productOrderMapper.getBuyOrderProduct(employeeId);
        for(Map wxOrder : ordermap){
            float payMoney = (float) wxOrder.get("pay_money");
            float orderMoney = (float) wxOrder.get("order_money");
            float profit = (float) wxOrder.get("profit");
            int day = (int) wxOrder.get("lock_time");
            //System.out.println("数据库获取的锁定时间:"+day);
            totalMoney = totalMoney+orderMoney;
            float e =(payMoney*profit*day)/365;
            payMoneyed = payMoneyed+payMoney;
            expectation = expectation+e;
            DecimalFormat decimalFormat=new DecimalFormat(".00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
            expectationStr=decimalFormat.format(expectation);//format 返回的是字符串
            System.out.println("expectationStr:"+expectationStr);
//            System.out.println(payMoney+"  "+profit);
//            System.out.println("e:"+e);

        }
//        DecimalFormat decimal=new DecimalFormat(".00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
//        String totalMoneyStr = decimal.format(totalMoney);
        //保留两位小数
        BigDecimal b1 = new BigDecimal(totalMoney);
        double totalMoneyStr = b1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();//保留两位小数


        BigDecimal b = new BigDecimal(expectation);
        float expectationStr1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();

        //计算每个产品的剩余额度，现在产品表中有总额度的字段，需要知道购买了每个产品的金额，就可以计算出剩余额度


        //使用的是关联查，先查询订单表中的数据
        QueryWrapper<WxProductOrder> queryWrapper = new QueryWrapper<>();
        List<WxProductOrder> lists = productOrderMapper.selectList(null);
        if(lists.isEmpty()){
            //为空 直接查询产品列表


        }

        //获取到所有的产品列表
        List<ProductDto> productDtos = new ArrayList<>();

        QueryWrapper<WxProduct> q = new QueryWrapper();
        q.orderByAsc("lock_time");
        List<WxProduct> productList = productMapper.selectList(q);
        for (WxProduct wxProduct : productList) {
            QueryWrapper<WxProductOrder> wrapper = new QueryWrapper();
            wrapper.eq("product_id", wxProduct.getProductId());
            wrapper.eq("order_status", 1);
            List<WxProductOrder> wxProductOrders = productOrderMapper.selectList(wrapper);
            ProductDto productDto = new ProductDto();

            float payMoney = 0.0f;
            for (WxProductOrder wxProductOrder : wxProductOrders) {
                payMoney += wxProductOrder.getPayMoney();
            }
            ProductDto productDto1 = new ProductDto();
            //计算剩额度
            float remain = wxProduct.getTotalQuota() - payMoney;
            DecimalFormat decimal=new DecimalFormat(".00 ");//构造方法的字符格式这里如果小数不足2位,会以0补足.
            String remainStr = decimal.format(remain);

            productDto1.setRemainingQuota(Double.parseDouble(remainStr));
            productDto1.setProductName(wxProduct.getProductName());
            DecimalFormat df = new DecimalFormat("0%");
            String r = df.format(wxProduct.getProfit());
            System.out.println("r:"+r);
            productDto1.setProfit(wxProduct.getProfit());
            productDto1.setProfitFormat(r);
            productDto1.setLockTime(wxProduct.getLockTime());
            productDtos.add(productDto1);

        }
                //findBuyProductInfoList();
//        for(ProductDto p : productList){
//            String productName = p.getProductName();
//            int lockTime = p.getLockTime();
//            float profit = p.getProfit();
//            DecimalFormat df = new DecimalFormat("0%");
//            String r = df.format(profit);
//            System.out.println("r:"+r);
//            //获取总额度
//            float totalQuato = p.getTotalQutao();
//            //获取已购买的金额
//            float buyed = p.getBuyed();
//            //计算当前产品的剩余额度（总额度-已购买的金额）
//            float remain = totalQuato-buyed;
//
//            DecimalFormat decimal=new DecimalFormat(".00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
//            String remainStr = decimal.format(remain);
////            BigDecimal bigDecimal = new BigDecimal(remain);
////            float remainStr = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
//            //创建ProductDto对象
//            ProductDto productDto = new ProductDto();
//            productDto.setProductName(productName);
//            productDto.setProfit(profit);
//            productDto.setProfitFormat(r);
//            productDto.setLockTime(lockTime);
//            productDto.setTotalQutao(totalQuato);
//            productDto.setBuyed(buyed);
//            //productDto.setRemainingQuota(remainingQuota);
//            //productDto.setRemainingQuota(Double.parseDouble(remainingQuotaStr));
//            productDto.setRemainingQuota(Double.parseDouble(remainStr));
//            list.add(productDto);
//
//        }

        System.out.println("expectation:"+expectation);


        //map.put("expectationMoney",expectation);
        map.put("expectationMoney",expectationStr1);
        //map.put("totalMoney",totalMoney);
        map.put("totalMoney",totalMoneyStr);
        map.put("list",productDtos);

        return CommonResult.success(map);
    }

    /**
     *产品详情页 当前产品的的剩余额度
     * @Author yu
     * @date 2021/9/29 12:17
     * @Param [productName]
     * @return com.mt.fpb.model.vo.CommonResult
     **/

    @ResponseBody
    @GetMapping("/dataShow")
    public CommonResult dataShow(String productName) {

        Map<String,Object> responseMap = new HashMap<>();
        Map<String,Object> map = productMapper.findBuyProrductInfo(productName);
        System.out.println(map.isEmpty());

        if(map.get("productName")==null){

            return CommonResult.fail(500,"该产品不存在");
        }
        double totalQutao = (double) map.get("totalQutao");//totalQutao


        double buyed = (double) map.get("buyed");
        double remain = totalQutao-buyed;
        responseMap.put("remain",remain);


        return CommonResult.success(responseMap);
    }


    @ResponseBody
    @GetMapping("/select")
    public CommonResult planAdjustDetail(String productName) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("product_name", productName);
        WxProduct wxProduct = productMapper.selectOne(wrapper);
        return CommonResult.success(wxProduct);
    }

}
